from django_redis import get_redis_connection
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
import random

from djangoProject09.settings import RONG_LIAN_YUN
from user.models import UserModel
from djangoProject09.utils import RongLianYun
from user.serializers import SmsLoginSerializers


# 发送短信验证码
class SmsCodeView(APIView):
    def get(self, request, phone):
        # 将验证码保存到数据库redis
        redis = get_redis_connection("sms_code")

        # redis 过期时间
        ttl = redis.ttl(f"interval_{phone}")
        print('---------------- redis 过期时间 -----------------')
        print(ttl)
        if ttl != -2:   # 验证码未过期，
            return Response({"msg": "验证码发送过于频繁，请稍后再试！", "code": 201})

        # 判断短信
        code = f"{random.randint(0, 9999):04d}"
        print('---------------------------------------------------------code:')
        print(code)
        # 导入容联云通讯短信接口
        rong_lian_class = RONG_LIAN_YUN
        tid = rong_lian_class.get("tid") # 短信模板ID
        print('---------------- tid -----------------')
        print(tid)
        expire = rong_lian_class.get('time') # 300 验证码有效期 单位：秒 英文单位-second
        expire_time = expire // 60 # 转换为分钟单位

        content = (code, expire)    # 短信内容 验证码+有效期




        pipe = redis.pipeline()  # 创建管道
        pipe.multi()             # 开启事务
        redis.setex(f"sms_{phone}", expire, code)  # 设置验证码 有效期 单位：秒 英文单位-second
        redis.setex(f"interval_{phone}", expire, code)  # 设置验证间隔 有效期 单位：秒 英文单位-second
        pipe.execute()           # 执行管道

        # 发送短信
        RongLianYun.send_message(tid, phone, content)
        print('---------------- send_result -----------------')

        return Response({"msg": "验证码发送成功"})

# 短信登录
class SmsLoginApiView(APIView):

    def post(self, request):
        data = request.data
        print("-----------post----- data -----------------")
        print(data)
        ser = SmsLoginSerializers(data=data)
        if ser.is_valid():
            ser.save()
            return Response({"msg": "登录成功","code": 200,"data":ser.data})
        else:
            return Response({"msg": "登录失败","code": 201,"error":ser.errors})


